var app = getApp();
import { base64src } from '../../utils/base64src.js'
Page({
  data: {
    qty:"1",
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    duration: 1000,
    res: [],
    display: "none",
    windowWidth: 280,
    windowHeight: 461,
    shareImgSrc: null,
    img_qcord:"",
    cart_num:0,
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},//
    loadList:false,
    type: "",
    id:'',
    item:"",
    loadingTxt: '',
    noMoreData: false,
    page: 1,
    size: 4
  },

  lessclick: function(){
    let qty=this.data.qty;
    if(qty == 1){
      return false;
    }

    let num=qty-1;
    this.setData({
      qty:num
    })
  },

  showshare:function(){
    var that = this;
    that.setData({
      hideModal: false
    })
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn();//调用显示动画
    }, 200)
  },

  cancel: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown();//调用隐藏动画   
    setTimeout(function () {
      that.setData({
        hideModal: true
      })
    }, 120)//先执行下滑动画，再隐藏模块
  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },

  addclick: function () {
    let qty = this.data.qty;

    let num = parseFloat(qty)+1;
    this.setData({
      qty: num
    })
  },

  add_cart:function (){
    let qty = this.data.qty;
    let id = this.data.id;
    let item =this.data.item;
    var that = this;
      wx.showLoading({
        title: '加载中...',
      })
  
    let token = wx.getStorageSync('token');
    if (token) { 
    app.getUserToken(function (err, token) { 
      wx.request({
        url: app.globalData.url +'/index.php?_m=checkout/cart/add_cart&v=v20190909b',
        data: { id: id, qty: qty, auth_token: token},
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },

        method:'POST',
        success: (res) => {
          wx.hideLoading();
           if (res.data.status == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.add_cart();
           } else if (res.data.code == 0) {
             wx.showModal({
               title: '加入购物车成功',
               content: '是否进入购物车',
               success(res) {
                 if (res.confirm) {
                   wx.switchTab({
                     url: '../cart/cart'
                   })
                 }
               }
             })
           }
        }
      })
    })
    }else{
      wx.hideLoading();
      var cartItems = wx.getStorageSync('cartItems') || []
      var exist = cartItems.find(function (ele) {
        return ele.id === id
      })

      if (exist) {
        //如果存在，则增加该货品的购买数量
        exist.qty = parseInt(exist.qty) + qty
      } else {
        //如果不存在，传入该货品信息
        cartItems.push({
          id: id,
          qty: qty,
          name: item.name,
          img_url: item.img_url,
          price: item.price,
          old_price: item.old_price
        })
      }
      wx.setStorage({
        key: 'cartItems',
        data: cartItems,
        success: function (res) {
          //添加购物车的消息提示框
          wx.showModal({
            title: '加入购物车成功',
            content: '是否进入购物车',
            success(res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '../cart/cart'
                })
              }
            }
          })
        }
      })
    }
  },

  goCart:function(e){
    wx.switchTab({
      url:'../cart/cart'
    })
  },
  goHome: function (e) {
    wx.switchTab({
      url: '../index/index'
    })
  },

  addCart: function (e) {
    let id = e.target.id;
    let img_url = e.target.dataset.img;
    let price = e.target.dataset.price;
    let old_price = e.target.dataset.oldprice;
    let name = e.target.dataset.name;
    let qty = 1;
    var that = this;
      wx.showLoading({  
        title: '加载中...',
      })
  
    let token = wx.getStorageSync('token');
    if (token) {
    app.getUserToken(function (err, token) { 
      wx.request({
        url: app.globalData.url +'/index.php?_m=checkout/cart/add_cart&v=v20190909b',
        data: { id: id, qty: qty, auth_token: token},
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: (res) => {
          wx.hideLoading();
          if (res.data.status == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.addCart();
          } else if (res.data.code == 0) {
            wx.showToast({
              title: '加入购物车成功',
              icon: 'none',
              duration: 1500
            })
            setTimeout(function () {
              wx.hideToast()
            }, 1500)
          }
        }
      })
    })
    }else{
      wx.hideLoading();
      var cartItems = wx.getStorageSync('cartItems') || []
      var exist = cartItems.find(function (ele) {
        return ele.id === id
      })

      if (exist) {
        //如果存在，则增加该货品的购买数量
        exist.qty = parseInt(exist.qty) + qty
      } else {
        //如果不存在，传入该货品信息
        cartItems.push({
          id: id,
          qty: qty,
          name: name,
          img_url: img_url,
          price: price,
          old_price: old_price
        })
      }
      wx.setStorage({
        key: 'cartItems',
        data: cartItems,
        success: function (res) {
          //添加购物车的消息提示框
          wx.showToast({
            title: '加入购物车成功',
            icon: 'none',
            duration: 1500
          })
          setTimeout(function () {
            wx.hideToast()
          }, 1500)
        }
      })
    }
  },

  getPorducts(options) {
    var that = this;
    wx.showLoading({
      title: '加载中...'
    })
    wx.request({
      url: app.globalData.url +'/index.php?_m=shop/product/get_item&id=' + options,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },

        data: {},
        method: 'POST',
        success: (res) => {
          if (res.data.code == 0){
            wx.hideLoading()
            if (!res.data.data.item){
              that.setData({
                loadList: true,
                item: null,
              })
              return false;
            }
            that.setData({
              loadList: true,
              item: res.data.data.item,
              imgUrls: res.data.data.item.img_urls.split(",")||[],
              id: res.data.data.item.id
            })
          }
        }
      })
  },

  getcarts() {
    var that = this;

      wx.request({
        url: app.globalData.url +'/index.php?_m=checkout/cart/get_cart',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: {},
        success: (res) => {
          if (res.data.status == 401) {
            // 清空授权token
            app.globalData.token = null
            wx.removeStorageSync('token')
            that.getcarts(prid, qty);
          } else if (res.data.code == 0) {
            that.setData({
              cart_num: res.data.data.cart_count,
            })
          }
        },
        fail: (res) => {
          wx.showToast({
            title: '获取借口失败',
            duration: 2000
          })
        }
      })
  },

  getRelative() {
    var that = this;
    var page = this.data.page;
    var size = this.data.size;
      wx.request({
        url: app.globalData.url +'/index.php?_m=shop/product/listing',
        data: { size: size, page: page },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'get',
        success: (res) => {
           if (res.data.code == 0) {
            let goods = [];
            if (page == 1) {
              goods = res.data.data;
            } else {
              goods = that.data.res.concat(res.data.data);
            }

            that.setData({
              res: goods
            });

            if (res.data.data.length < that.data.size) {

              that.setData({

                loadingTxt: '没有更多内容',

                noMoreData: true,

              });

            }
            
          }
        }
      })
  },

  onPullDownRefresh: function () {
    // 初始化信息
    this.getRelative();

    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 1000)

  },

  onReachBottom: function () {

    if (!this.data.noMoreData) {

      this.data.page = this.data.page + 1;

      this.getRelative(true);

    };

  },

 
  getQcord(options){
    let that=this;
    wx.cloud.callFunction({
      name: 'getImage',  
      data: {   
        page:"pages/item/item",
        id: options
      },
      complete: res => {
        
        let img = wx.arrayBufferToBase64(res.result.buffer);

        base64src('data:image/jpg;base64,' + img, res => {
           that.setData({
             img_qcord:res
           })
        });
      }
    })
  },


  onLoad: function (options) {
    let id = 0;
    if (options.id){
       id = options.id; 
    }

    if (options.scene){
      const scene = decodeURIComponent(options.scene)
     
      id = scene.substring(3);
    }
    
    this.getPorducts(id);
    this.getcarts();
    this.getRelative();
    this.getQcord(id);
  },
  
  onShareAppMessage: function () {
    return {
      title: "￥" + this.data.item.price+" "+this.data.item.name,
      path: '/pages/item/item?id=' + this.data.id
    }
  },
  onShareTap: function (event) {
    
    wx.showLoading({
      title: '生成中',
    })
    this.setData({
      display: "block",
    })
    var that = this;
  
     wx.getImageInfo({
       src: that.data.item.img_url,
       success: function (sres) {
         that.onshow("智汇GO", sres.path);
       }
     })  
  },
  
  onshow: function (name, img) {
    
    var that = this;
    //1. 请求后端API生成小程序码
    //2. canvas绘制文字和图片
    const ctx = wx.createCanvasContext('myCanvas');
    //背景图

    // var bgImgPath = this.data.item.img_url;
    var bh_bg = "../../images/hb-bg.png";
    ctx.drawImage(bh_bg, 0, 0, this.data.windowWidth, 461);

     var imgPath = that.data.img_qcord;//二维码
     ctx.drawImage(img, 32.5, 60, 220, 200);

     ctx.setFontSize(15)
     ctx.setFillStyle('#E83731')
     ctx.fillText("￥" + this.data.item.price, 111.5, 290)
     ctx.fillText("￥" + this.data.item.price, 111, 290.5)
     ctx.fillText("￥" +this.data.item.price, 111, 290)

    //ctx.setFillStyle('white')
    //ctx.fillRect(0, 280, 300, 120);
    ctx.drawImage(imgPath, 15, 370, 70, 70);

    //ctx.save()
    //ctx.beginPath()
    //ctx.arc(30, 308, 15, 0, 2 * Math.PI)
    //ctx.clip()
    // ctx.drawImage("../../images/logo.png", 18, 290, 30, 30)
    //ctx.restore()
    //绘制字体
    // ctx.setFontSize(13)
    // ctx.setFillStyle('#6F6F6F')
    // ctx.fillText(name, 10, 338)

    var td = Math.ceil(this.data.windowWidth / 20);
    console.log(td);
    var tr = Math.ceil(this.data.windowHeight / td);
    
    for (var i = 0; i < tr; i++) {
      var txt = {
        x: 140,
        y: 310 + (i * 10),
        color: '#111111',
        size: '13',
        align: 'left',
        baseline: 'top',
        text: this.data.item.name.substring(i * td, 14),
        bold: false
      };
      if (i < 3) {
        if (i== 1) {
          //txt.text = txt.text
           txt.text = txt.text.substring(0, txt.text.length - 3);
        }
        ctx.save();
        ctx.setFontSize(13)
        ctx.setFillStyle('#000000')
        ctx.setTextAlign('center');
        ctx.setTextBaseline('top');
        ctx.fillText(txt.text, txt.x, txt.y);
      }
    }
    // ctx.setFontSize(11)
    // ctx.setFillStyle('#999999')
    // ctx.fillText('智汇GO', 157, 415)
    ctx.draw(false, setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: that.data.windowWidth,
        height: that.data.windowHeight,
        destWidth: that.data.windowWidth * 3,
        destHeight: that.data.windowHeight * 3,
        canvasId: 'myCanvas',
        success: function (res) {
          console.log(res.tempFilePath);
          wx.hideLoading();
          that.setData({
            shareImgSrc: res.tempFilePath
          })

        },
        fail: function (res) {
          wx.hideLoading();
          wx.showToast({
            title: '生成失败',
            icon: "none"
          })
        }
      })
    }, 200));
  },

  showLocal: function () {
    var that = this;
    console.log(that.data.shareImgSrc);
    wx.saveImageToPhotosAlbum({
      filePath: that.data.shareImgSrc,
      success(res) {
        wx.showModal({
          title: '存图成功',
          content: '图片成功保存到相册了，去发圈噻~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#21bba6',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            }

          }
        })
      }, fail: function () {
        wx.showToast({
          title: '保存失败',
          icon: "none"
        })
      }
    })
  },
  hideview: function () {
    this.setData({
      display: "none"
    })
  }

})